package cn.mumzone.pos.util;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.StringDef;
import android.text.TextUtils;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.mumzone.basic.util.DeviceIdUtils;
import cn.mumzone.pos.AppConstants;

/**
 * Author Chaney
 * Date   2017/3/8 下午2:05.
 * EMail  qiuzhenhuan.hi@gmail.com
 */

public class FileUtil {


    /**
     * 图片缓存目录
     */
    public static final String FOLD_IMAGES = "images";

    /**
     * ACache缓存目录
     */
    public static final String FOLD_ACACHE = "acache";

    /**
     * 网络请求缓存目录
     */
    public static final String FOLD_API = "api";

    /**
     * APK下载目录
     */
    public static final String FOLD_APK_DOWNLOAD = "apk";

    /**
     * 裁剪过的图片地址
     */
    public static final String FOLD_PHOTO_CUT = "cut";

    /**
     * 对象缓存地址
     */
    public static final String FOLD_OBJECT = "object";

    /**
     * 判断是否存在应用外部存储
     *
     * @return
     */
    private static final String SDCARD_MNT = "/mnt/sdcard";

    private static final String SDCARD = "/sdcard";


    public static boolean isExistSDCard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    public static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mlwapp/";


    public static File getResourseCacheDir(Context context, @ResourseCache String uniqueName) {
        String cachePath = "";
        if(AppConstants.TEMP_EQUI_MODEL.equals("BY")){
            cachePath = isExistSDCard() ? getExternalCacheDir(context).getPath()
                    : context.getCacheDir().getPath();
        }else {
            cachePath = context.getExternalCacheDir().getPath();
        }
        File fold = new File(cachePath + File.separator + uniqueName);
        if (!fold.exists()) {
            fold.mkdirs();
        }
        return fold;
    }

    public static File getDataCacheDir(Context context, @DataCache String uniqueName) {
        final String cachePath = context.getCacheDir().getPath();
        File fold = new File(cachePath + File.separator + uniqueName);
        if (!fold.exists()) {
            fold.mkdirs();
        }
        return fold;
    }

    public static File getResourseCacheFile(Context context, String pathName, String fileName) throws IOException {
        File file = null;
        final String cachePath = isExistSDCard() ? getExternalCacheDir(context).getPath()
                : context.getCacheDir().getPath();
        File fold = new File(cachePath + File.separator + pathName);
        if (!fold.exists()) {
            fold.mkdirs();
        }
        file = new File(fold.getPath() + File.separator + fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        return file;
    }


    /**
     * 删除目录下的所有子目录及文件
     *
     * @param fold
     */
    public static void deleteFold(File fold) {
        if (fold != null && fold.isDirectory()) {
            File[] files = fold.listFiles();
            if (null == files)
                return;
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteFold(file);
                } else {
                    file.delete();
                }
            }
        }
    }


    public static File getApkFile(Context context){
        String versionName = DeviceIdUtils.getLocalVersionName(context);
        return new File(getResourseCacheDir(context,FOLD_APK_DOWNLOAD), String.format("android_pos_%s.apk",versionName));
    }

    /**
     * 清除APK下载目录的文件
     *
     * @param context
     */
    public static void clearApkDownloadPath(Context context) {
        File fold = FileUtil.getResourseCacheDir(context, FileUtil.FOLD_APK_DOWNLOAD);
        if (fold != null && fold.isDirectory()) {
            File[] files = fold.listFiles();
            if (null == files)
                return;
            for (File file : files) {
                file.delete();
            }
        }
    }

    public static void saveBitmap(Bitmap bitmap, File file) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos);
            bos.flush();
            bos.close();
            bitmap.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取缓存目录
     *
     * @param context
     * @return
     */
    private static File getExternalCacheDir(Context context) {
        File fold = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + context.getPackageName() + "/cache/");
        if (!fold.exists()) {
            fold.mkdir();
        }
        return fold;
    }

    public static boolean save(InputStream is, String savePath, long length) throws IOException {
        int total = 0;
        FileOutputStream fos = null;
        try {
            byte[] buff = new byte[1024];
            int len;
            fos = new FileOutputStream(new File(savePath));
            while ((len = is.read(buff)) > 0) {
                fos.write(buff, 0, len);
                total += len;
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            // return false;
            throw e;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (total != length) {
                throw new IOException("下载不完整，应下" + length + ", 实下" + total);
            }
        }
    }


    /**
     * 创建一个新的文件
     *
     * @param path
     * @return
     */
    private static boolean createFile(String path) {

        File file = new File(path);
        if (null != file && !file.exists()) {
            if (!file.getParentFile().exists()) {
                return file.getParentFile().mkdirs();
            }
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 获取图片的扩展名
     *
     * @param picPath
     * @return
     */
    private static String getPicName(String picPath) {
        if (TextUtils.isEmpty(picPath)) {
            return "";
        }
        int indext = picPath.lastIndexOf(".");
        return picPath.substring(indext + 1);
    }

    /**
     * 获取文件的标准的路径
     *
     * @return
     */
    private static String getAbsoluteImagePath(Activity activity, Uri uri) {
        String picPath = "";
        String[] projection = new String[]{MediaStore.Audio.Media.DATA};
        Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
        if (null != cursor && cursor.getCount() > 0 && cursor.moveToFirst()) {
            picPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
        }
        return picPath;
    }

    /**
     * 获取图片的绝对地址
     *
     * @param uri 图片的 uri
     * @return 返回图片的地址
     */
    private static String getAbsolutePathFromNoStandardUri(Uri uri) {
        String path = null;
        String picPath = uri.toString();
        picPath = Uri.encode(picPath);
        String file1 = "f://" + SDCARD + File.separator;
        String file2 = "f://" + SDCARD_MNT + File.separator;
        if (!TextUtils.isEmpty(picPath)) {
            if (picPath.startsWith(file1)) {
                path = Environment.getExternalStorageDirectory().getPath() + File.separator + picPath.substring(file1.length());
            } else if (picPath.startsWith(file2)) {
                path = Environment.getExternalStorageDirectory().getPath() + File.separator + picPath.substring(file2.length());
            }
        }
        return path;

    }

    /**
     * 删除创建的图片文件
     *
     * @param url
     */

    public static void detelePic(Context context, String url) {
        File file = new File(url);
        if (file.exists()) {
            file.delete();
            // 清除残留
            context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media.DATA + "=?", new String[]{url});
        }
    }

    /**
     * 保存bitmap
     *
     * @param bitmap
     * @param fileName
     * @return
     */
    public static String saveBitmap(Bitmap bitmap, String fileName) {
        String state = Environment.getExternalStorageState();
        if (!TextUtils.isEmpty(state) && state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(PATH);
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            File file = new File(Environment.getDataDirectory().getAbsolutePath() + "/data/");
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        String strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 图片的名字
        String picFileName = "app_crop" + strDate + "." + fileName + ".jpg";
        picFileName = PATH + picFileName;
        if (createFile(picFileName)) {
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(picFileName));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                bos.flush();
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return picFileName;

    }


    @StringDef({FOLD_IMAGES, FOLD_PHOTO_CUT,FOLD_OBJECT,FOLD_APK_DOWNLOAD})
    @Retention(RetentionPolicy.SOURCE)
    @interface ResourseCache {

    }

    @StringDef({FOLD_API, FOLD_ACACHE})
    @Retention(RetentionPolicy.SOURCE)
    @interface DataCache {

    }
}
